<template>
  <div class="home">
    <Layout :style="{padding: '0 24px 24px'}">
      <Breadcrumb :style="{margin: '24px 0'}">
        <BreadcrumbItem>产品中心</BreadcrumbItem>
        <BreadcrumbItem>红包管理</BreadcrumbItem>
        <Button type="success" class="" @click="AddQrcode">添加红包</Button>
      </Breadcrumb>
      <Content :style="{padding: '24px 182px 24px 24px', minHeight: this.$h.GetContentBodyHeight()+'px', background: '#fff'}">
        <Table :loading="loading_" border :columns="columns7" :data="Redbao" stripe></Table>
        <Page :total="total" :page-size="pagesize" @on-change="changpage" show-total/>

        <!--添加二维码标题-->
        <Modal
          v-model="QrcodeFlag"
          title="添加红包"
          @on-ok="DetermineQrcode">
          <Form :label-width="120">
            <FormItem label="红包活动标题">
              <Input v-model="ui_title" placeholder="红包活动标题(中文)"></Input>
            </FormItem>
            <FormItem label="红包活动内容">
              <Input v-model="ui_body" placeholder="红包活动内容"></Input>
            </FormItem>
            <FormItem label="设置红包数量">
              <Input v-model="red_sum_num" placeholder="设置红包数量" number></Input>
            </FormItem>
            <FormItem label="设置金额">
              <Input v-model="total_amount" placeholder="设置金额" number></Input>
            </FormItem>
            <FormItem label="红包发送方式">
              <Select v-model="redtypeval" placeholder='微信红包' style="width:200px">
                <Option v-for="item in redtype" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
            <FormItem label="红包状态">
              <Select v-model="redtypeflag" placeholder='开启' style="width:200px">
                <Option v-for="item in redtypeflagarr" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>

          </Form>
        </Modal>

        <!--添加二维码图片-->
        <Modal
          v-model="QrcodeFlagImage"
          title="请添加背景图"
          @on-ok="DetermineQrcodeImg">
          <div class="anti_">
            <img :src="backimg" ref="img_" alt="" class="el_img"/>
            <input ref="list" @change="onFileChange($event)" type='file' name="thumbnail"
                   accept='image/jpeg image/x-png' class=" pic_add"/>
          </div>
        </Modal>

      </Content>
    </Layout>
  </div>
</template>
<script>
  import backimg from "~/timg.jpg";
  import {
    mapGetters
  } from 'vuex'

  export default {
    props: {},
    components: {},
    data() {
      return {
        redtypeflag: '1',
        redtypeflagarr: [
          {
            value: '1',
            label: '开启'
          },
          {
            value: '2',
            label: '关闭'
          },
        ],

        redtypeval: '1',
        redtype: [
          {
            value: '1',
            label: '微信红包'
          },
          {
            value: '2',
            label: '微信到零钱'
          },
        ],
        gudiing_img: backimg,
        ui_title: '',
        ui_body: '',
        red_sum_num: '',
        total_amount: '',
        wishing: '送红包', //微信端红包祝福语
        act_name: '红包', //微信端红包活动名称
        remark: '送红包', //微信端备注
        Redenvelopes: 'Redbao/background/',//红包名称
        GetGoods_Add_flag: true,
        backimg,
        input_val: '',//临时储存 IMG
        QrcodeFlag: false,//添加二维码状态
        QrcodeFlagImage: false,//添加二维码图片状态
        loading_: false,
        total: 0,//数据总条数
        pagesize: 10,//每页条数
        Redbao: [],//红包列表
        Alldata: [],//数据总和
        RidId: '',//创建红包的ID
        columns7: [
          {
            title: '客户端显示标题',
            key: 'ui_title',
            width: 120,
          },
          {
            title: '客户端显示内容',
            key: 'ui_body',
            width: 120,
          },

          {
            title: '当前红包剩余数量',
            key: 'red_now_num',
            width: 100,
          },
          {
            title: '红包金额',
            key: 'total_amount',
            width: 100,
          },
          {
            title: '红包总数量',
            key: 'red_sum_num',
            width: 100,
          },
          {
            title: '红包发送方式',
            key: 'type',
            width: 120,
            render: (h, params) => {
              return h('div', [
                h('strong', params.row.type == '1' ? '微信红包' : '微信到零钱')
              ]);
            }
          },
          {
            title: '红包发送状态',
            key: 'reds_status',
            width: 120,
            render: (h, params) => {
              return h('div', [
                h('strong', params.row.reds_status == '1' ? '开启' : '关闭')
              ]);
            }
          },
          {
            title: '添加时间',
            key: 'created_at',
            width: 160,
          },
          {
            title: '操作',
            key: 'action',
            width: 300,
            align: 'center',
            render: (h, params) => {
              return h('div', [

                h('Button', {
                  props: {
                    type: 'success',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.operation(params.row);
                    }
                  }
                }, '导出'),

                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  }, style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.RedRecord(params.row);
                    }
                  }
                }, '扫码记录'),
                h('Button', {
                  props: {
                    type: 'warning',
                    size: 'small'
                  }, style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.UpdateImg(params.row);
                    }
                  }
                }, '修改图片'),

                h('Button', {
                  props: {
                    type: params.row.reds_status == 1 ? 'error' : 'primary',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.redtypefn(params.row);
                    }
                  }
                }, params.row.reds_status == 1 ? '关闭' : '开启'),
              ]);
            }
          }
        ],
      }
    },
    methods: {
      redtypefn(r) {
        var reds_status = '';
        switch (r.reds_status) {
          case '1':
            reds_status = '2';
            break;
          case '2':
            reds_status = '1';
        }

        this.http.post({
          'api': 'checkactivitystatus',
          'data': {
            'brid': r.id,
          },
        }).then((res) => {
          if (res.data.Response.code == 200) {
            let flag = '';
            switch (res.data.Response.data.reds_status) {
              case 1:
                flag = '已开启';
                break;
              case 2:
                flag = '已关闭';
                break;
            }
            ;
            this.Redbao.forEach((item) => {
              if (item.id == r.id) {
                item.reds_status = reds_status;
              }
            });
            this.$Notice.success({
              title: '操作成功',
              desc: res.data.Response.data.ui_title + '红包活动' + flag
            });
            console.log(res.data.Response.data.reds_status);
          }
        }, (err) => {
          if (err.request.response.Response.code == 500) {

          }
        });
      },
      changpage(page) {  //点击分页
        this.Redbao = this.Alldata.slice((page - 1) * this.pagesize, page * this.pagesize)
      },
      operation(row) { //  导出红包
        this.http.Excel({
          'api': 'downloadqrcodeurl',
          'data': {
            'id': row.id
          },
        }).then((res) => {
          this.$downLoad(res.data, `${row.ui_title}.csv`);
        }, (err) => {
          if (err.request.response.Response.code == 500) {

          }
        });
      },
      AddQrcode() {  //添加二维码
        this.QrcodeFlag = true;
        this.backimg = this.gudiing_img;
      },
      DetermineQrcode() {//确定添加二维码
        // console.log();

        var red_range = '';
        let reg = new RegExp("^[0-9]*$");
        // if (!reg.test(this.total_amount)) {
        //   this.$Message.info('设置金额格式不正确');
        //   return false
        // }

        if (!reg.test(this.red_sum_num)) {
          this.$Message.info('设置红包数量格式不正确');
          return false
        }

        if (this.Redbao.length == 0) {
          red_range = '1,' + this.red_sum_num.toString();
        } else {
          var range = this.Redbao.pop().red_range.split(",");
          var red_stat = parseInt(range[1]) + 1;
          var red_sotp = red_stat + this.red_sum_num;
          red_range = red_stat.toString() + ',' + red_sotp.toString();
        }

        this.http.post({
          'api': 'createred',
          'data': {
            'red_now_num': this.red_sum_num,
            'red_sum_num': this.red_sum_num,
            'red_range': red_range,
            'ui_title': this.ui_title,
            'ui_body': this.ui_body,
            'wishing': this.wishing,
            'act_name': this.act_name,
            'remark': this.remark,
            'total_amount': this.total_amount,
            'type': this.redtypeval,
            'status': this.redtypeflag
          },
        }).then((res) => {
          if (res.data.Response.code == 200) {
            this.RidId = res.data.Response.data.id;
            this.QrcodeFlagImage = true; //打开二维码 弹出框
          }
        }, (err) => {
          if (err.request.response.Response.code == 500) {
            this.$Notice.error({
              title: '创建失败',
              desc: err.request.response.Response.message + '，请充值！！'
            });
          }
        });

      },

      onFileChange(e) { // 二维码图片 Change事件
        var URL = window.URL || window.webkitURL;
        var imgURL = URL.createObjectURL(e.target.files[0]);
        var img_url = e.target;
        const isLt2M = img_url.files[0].size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('或者上传头像图片大小不能超过 2MB!');
        } else {
          this.backimg = imgURL;
          if (this.GetGoods_Add_flag == false) {
            //修改
            this.$img.SetParm(this.Redenvelopes + this.RidId).delete().then((res) => {
              },
              (ref) => {
                this.GetGoods_Add_flag = true;   //修改状态
              });
          }
          this.input_val = e;
        }
      },
      DetermineQrcodeImg() {//添加 二维码背景图
        this.$img.SetParm(this.Redenvelopes + this.RidId, this.input_val).create().then((res) => {
            if (res) {
              this.$Notice.success({
                title: '商品图片添加成功',
              });
              this.contentbody();
            }
          },
          (ref) => {
//            console.log(ref);
          })
      },
      UpdateImg(row) { //修改模板背景图
        this.RidId = row.id;
        this.QrcodeFlagImage = true; //打开二维码 弹出框
        this.GetGoods_Add_flag = false; //修改状态
        this.img_class(row.id);
      },
      img_class(r) {
        let url = this.$imgList.RedImage[r];
        let host = this.$ENV.UPLOADIMG;
        let res = `${host}${url}`;
        this.backimg = res;
      },
      RedRecord(row) { //扫码记录
        this.$store.commit('SetScavengingID', row.id);
        this.$router.push({
          path: '/RedRecord'
        });

      },

      contentbody() {

        this.http.post({
          'api': 'getredlist',
          'data': {},
        }).then((res) => {
          if (res.data.Response.code == 200) {
            this.Processingdata(res.data.Response.data)
          }
        }, (err) => {
          if (err.request.response.Response.code == 500) {
            this.$Notice.error({
              desc: err.request.response.Response.message
            });
          }
        });
      },
      Processingdata(data) {
        this.Alldata = data;
        this.total = data.length;//数据总条数
        this.Redbao = data.slice(0, this.pagesize);
      }
    },
    watch: {},
    computed: {
      ...mapGetters([
        'GetUserInfo'
      ]),
    },
    created() {

    },
    mounted() {
      this.contentbody();
    }
  }
</script>
<style scoped>
  .home {
    width: 100%;
    height: 100%;
  }

  .anti_ {
    width: 300px;
    margin: auto;
    height: 100%;
  }

  .anti_ img {
    width: 100%;
    height: 100%;
    display: block;
    background-size: 100% 100%;
  }

  .pic_add {
    /*width: 100%;*/
    /*height: 300px;*/
    /*position: relative;*/
    /*bottom: 300px;*/
    /*z-index: 9999;*/
    /*opacity: 0;*/
  }
</style>
